//
//  LocationManager.m
//  999-考勤定位
//
//  Created by 李晓东 on 2018/4/10.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "LocationManager.h"
#import "_99_考勤定位-Swift.h"
#import <CoreLocation/CoreLocation.h>
#import "AVOSCloud.h"

@interface LocationManager () <CLLocationManagerDelegate>
@property (nonatomic, strong) NSString *fuckYou;

@end

@implementation LocationManager{
    AVObject *_dateBase;
    CLLocationManager *_locationManager;
    BOOL _stopFlag;
    
}
NSString *systempVersion;
static LocalNotification *_locationNotification;

+ (instancetype)shareLocationManager {
    static dispatch_once_t onceToken;
    static LocationManager *locationManager;
    dispatch_once(&onceToken, ^{
        locationManager = [[LocationManager alloc]init];
        systempVersion = [UIDevice currentDevice].systemVersion;
        _locationNotification = [[LocalNotification alloc]init];
        [_locationNotification initLocalNotification];
        [_locationNotification createLocalNoti];
    });
    return locationManager;
}

- (instancetype)init{
    if (self = [super init]) {
        _locationManager = [[CLLocationManager alloc]init];
        [_locationManager setDelegate:self];
        [_locationManager setDistanceFilter:2];
        [_locationManager requestAlwaysAuthorization];
        [_locationManager setAllowsBackgroundLocationUpdates:YES];
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
    }
    return self;
}
- (void)startLocating{
//    if (_locationManager == nil) {
//        _locationManager = [[CLLocationManager alloc]init];
//        [_locationManager setDelegate:self];
//        [_locationManager setDistanceFilter:2];
//        [_locationManager requestAlwaysAuthorization];
//        [_locationManager setAllowsBackgroundLocationUpdates:YES];
//        [_locationManager setPausesLocationUpdatesAutomatically:NO];
//        _stopFlag = YES;
//    }
    _stopFlag = YES;
    [_locationManager startUpdatingLocation];
}

- (void)stopLocating{
//    if (_locationManager != nil) {
        if (_stopFlag != YES) {
            [_locationManager startUpdatingLocation];
        }
        _stopFlag = NO;
//    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
//    [_locationNotification sendNotificationWithContent:@"我在定位中"];

    if (_stopFlag) {

        CLLocation *location = locations.lastObject;
        
        _dateBase = [AVObject objectWithClassName:@"Location"];
        [_dateBase setObject:@(location.coordinate.latitude) forKey:@"lat"];
        [_dateBase setObject:@(location.coordinate.longitude) forKey:@"long"];
        [_dateBase setObject:systempVersion forKey:@"system_version"];
        
        [_dateBase saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            
            
        }];
    }
    
}

@end
